#include <stdio.h>
#include <regex.h>
#include <string.h>
#include <pcre.h>

int convert_msg_name(char *msg, char *ret);
int convert_msg_name2(char *msg, char *ret);

#define BUFMAX 1024

int main(){
	char *msg1 = "[Signatures name: ] [main class name: 100000000] [sub class name: 100400000]: 100400063";
	char *msg2 = "[Signatures name: ] [main class name: 010000000] : 010000063";
	char ret[BUFMAX];

	convert_msg_name(msg1,ret);
	convert_msg_name(msg2,ret);
}

int convert_msg_name(char *msg, char *ret)
{
	pcre *re = NULL;
	const char *error = NULL;
	char   *pattern = "[^0-9]*([0-9]{9})[^0-9]*([0-9]{9})?[^0-9]*([0-9]{9})";
	int erroroffset = 0; 
	int offsets[(3+1)*3];
	int offset,length;
	int rc;
	char *tmp;
	int i;

	re = pcre_compile(pattern, PCRE_CASELESS, &error, &erroroffset,NULL);

	if (re == NULL) {
		printf("PCRE compilation failed at offset %d: %s\n",erroroffset, error);
		return -1;
	}

	rc = pcre_exec(re, NULL, msg, strlen(msg), 0, 0, offsets, (3+1)*3);
	for (i = 1; i < rc; i++) {
		tmp = msg + offsets[2*i];  
		length = offsets[2*i+1] - offsets[2*i];  
		printf("$%2d: %.*s\n", i, length, tmp);  
	}  

	/*
	if (rc > 0) { 
		pcre_get_substring(msg, offsets, rc, 1, &tmp);
		offset = offsets[1*2];
		length = offsets[1*2+1] - offsets[1*2];
		strncpy(ret, msg + offset,length);
		printf("tmp=%s and length = %d\n",tmp,length);
		printf("ret=%s and length = %d\n",ret,length);
	} else {
		*ret = "";
	}    
	*/

	pcre_free(re);
	re = NULL;
	return 0;
}


int convert_msg_name2(char *msg, char *ret)
{
#define SUBSLEN 4
	regex_t     re; 
	regmatch_t  subs[SUBSLEN]; 
	char   *pattern = "[^0-9]*([0-9]{9})[^0-9]*([0-9]{9})?[^0-9]*([0-9]{9})";
	char        matched[BUFMAX];
	char        errbuf[BUFMAX];
	int         err,len,i;

	err = regcomp(&re, pattern, REG_EXTENDED);
	if (err) {
		len = regerror(err, &re, errbuf, sizeof(errbuf));
		printf("error: regcomp: %s\n", errbuf);
		return -1; 
	}   
	printf("Total has subexpression: %ld\n", re.re_nsub);
	/* 执行模式匹配 */
	err = regexec(&re, msg, (size_t) SUBSLEN, subs, 0); 

	if (err == REG_NOMATCH) { /* 没有匹配成功 */
		printf("Sorry, no match ...\n");
		regfree(&re);
		return -1; 
	} else if (err) {  /* 其它错误 */
		len = regerror(err, &re, errbuf, sizeof(errbuf));
		printf("error: regexec: %s\n", errbuf);
		return -1; 
	}   

	/* 如果不是REG_NOMATCH并且没有其它错误，则模式匹配上 */
	printf("\nOK, has matched ...\n\n");
	for (i = 0; i <= re.re_nsub; i++) {
		len = subs[i].rm_eo - subs[i].rm_so;
		if (i == 0) {
			printf ("begin: %d, len = %d  ", subs[i].rm_so, len); /* 注释1 */
		} else {
			printf("subexpression %d begin: %d, len = %d  ", i, subs[i].rm_so, len); 
		}   
		memcpy (matched, msg + subs[i].rm_so, len);
		matched[len] = '\0';
		printf("match: %s\n", matched);
	}   

	regfree(&re);   /* 用完了别忘了释放 */
	return 0;
}
